package com.lcke.common.config;

import com.zaxxer.hikari.HikariDataSource;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.*;
import org.springframework.core.annotation.Order;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@MapperScan(basePackages = "com.lcke.*.dao")
public class LemonDataSource {


    @Bean(LemonCnt.DS_KEY_ONE)
    @ConfigurationProperties(prefix = "spring.datasource.one")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean(LemonCnt.DS_KEY_TWO)
    @ConfigurationProperties(prefix = "spring.datasource.two")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }


    @Primary
    @DependsOn({LemonCnt.DS_KEY_TWO, LemonCnt.DS_KEY_ONE})
    @Bean(name = "dynamicDataSource")
    public DataSource dynamicDataSource() {
        LemonDynamicDs dynamicDataSource = new LemonDynamicDs();

        // 配置多数据源
        Map<Object, Object> dsMap = new HashMap<>();
        dsMap.put(LemonCnt.DS_KEY_ONE, masterDataSource());
        dsMap.put(LemonCnt.DS_KEY_TWO, slaveDataSource());
        dynamicDataSource.setTargetDataSources(dsMap);

        // 默认数据源
        dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
        return dynamicDataSource;
    }


}


